package com.xj.algorithm.leetcode;

/**
 * 七进制数
 */
public class L504_7进制数 {

    /**
     * 给定一个整数，将其转化为7进制，并以字符串形式输出。
     *
     * 示例 1:
     *
     * 输入: 100
     * 输出: "202"
     * 示例 2:
     *
     * 输入: -7
     * 输出: "-10"
     * 注意: 输入范围是 [-1e7, 1e7] 。
     */
    public static void main(String[] args) {
        System.out.println(convertToBase7(100));
        System.out.println(convertToBase7(-7));
        System.out.println(convertToBase7(-13));
        System.out.println(convertToBase7(0));

        System.out.println(convertToBase7Good(100));
        System.out.println(convertToBase7Good(-7));
        System.out.println(convertToBase7Good(-13));
        System.out.println(convertToBase7Good(0));
    }

    //自己的解法：不停除以7，反向输出。区分正负数
    public static String convertToBase7(int num) {
        if(num==0){
            return "0";
        }

        String pre="";
        if(num<0){
            pre="-";
            num=num*-1;
        }
        String res="";
        while (num!=0){
            res=(num%7)+res;
            num=num/7;
        }
        return  pre+res;
    }

    //精彩解法：递归
    public static String convertToBase7Good(int num) {
        if (num < 0) return "-" + convertToBase7Good(-1 * num);
        if (num < 7) return String.valueOf(num);
        return convertToBase7Good(num / 7) + (num % 7);
    }

}
